package configlogic

import (
	"context"
	"math"

	model "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/config"
	schema "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/config"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetConfigChangeLogLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	repo       *model.ConfigInoutTypeLog
	configRepo *model.InoutModel
}

func NewGetConfigChangeLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetConfigChangeLogLogic {
	return &GetConfigChangeLogLogic{
		ctx:        ctx,
		svcCtx:     svcCtx,
		Logger:     logx.WithContext(ctx),
		repo:       model.NewConfigInoutTypeLog(ctx, svcCtx.Db),
		configRepo: model.NewInoutModel(ctx, svcCtx.Db),
	}
}

func (l *GetConfigChangeLogLogic) GetConfigChangeLog(in *rpc.GetConfigChangeLogReq) (*rpc.GetConfigChangeLogReps, error) {
	list, err := l.repo.GetPageList(in.GetPageReq().GetPageNo(), in.GetPageReq().GetPageSize())
	if err != nil {
		return nil, err
	}
	var configIds []int64
	for _, row := range list {
		configIds = append(configIds, row.ConfigId)
	}
	configInfos, err := l.configRepo.FindByIds(configIds)
	if err != nil {
		return nil, err
	}
	var configInfoMaps = make(map[int64]*schema.ConfigInoutType)
	for _, cnf := range configInfos {
		configInfoMaps[cnf.Id] = cnf
	}

	total, err1 := l.repo.GetTotal()
	if err1 != nil {
		return nil, err1
	}
	var result []*rpc.ConfigChangeLog
	for _, row := range list {
		configInfo := configInfoMaps[row.ConfigId]
		result = append(result, &rpc.ConfigChangeLog{
			Id:         row.Id,
			Name:       configInfo.Name,
			TypeId:     configInfo.TypeId,
			OldValue:   row.OldValue,
			NewValue:   row.NewValue,
			CreatedUid: row.CreatedUid,
			CreateTime: row.CreatedAt,
			Ip:         row.Ip,
			IpPlace:    row.IpPlace,
		})
	}
	return &rpc.GetConfigChangeLogReps{
		List: result,
		Pageination: &rpc.Pagination{
			PageSize:  uint32(in.GetPageReq().GetPageSize()),
			Page:      uint32(in.GetPageReq().GetPageNo()),
			Total:     total,
			TotalPage: int64(math.Ceil(float64(total) / float64(in.GetPageReq().GetPageSize()))),
		},
	}, nil
}
